import { createRouter, createWebHashHistory } from "vue-router";
import globalRoutes from "./globalRoutes";
import mainRoutes from "./mainRoutes";
import store from "@/store";
import { ADD_BAR } from "@/store/modules/tabbar/type";
import { computed, ref } from "vue";
import { buildFullPath } from "@/utils/queryParams";

const router = createRouter({
    history: createWebHashHistory(),
    scrollBehavior: () => ({ y: 0 }),
    isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
    routes: globalRoutes.concat(mainRoutes),
});

const hasClickMenuList = computed(() => store.getters.hasClickMenuList);
const ignore_bar_list = ref(["Login", "404", "Zone", "ZoneInit", "Register"]);
// 路由守卫 - 添加标签页
router.beforeEach((to, from, next) => {
    // 添加标签到标签栏
    // 通过菜单code 转换barName
    // 获取本地点击的路由
    let clickRoute = hasClickMenuList.value.find(
        (item) => item.clickCode === to.name,
    );
    console.log("to:" + to);
    if (ignore_bar_list.value.indexOf(to.name) === -1) {
        // 构造包含查询参数的完整路径
        const fullPathWithQuery =
            to.fullPath || buildFullPath(to.path, to.query);
        store.dispatch("tabbar/" + ADD_BAR, {
            barCode: fullPathWithQuery,
            barName: clickRoute?.clickName || to.meta?.title || to.name,
            name: to.name,
            path: to.path,
            fullPath: fullPathWithQuery,
            meta: to.meta,
            title: to.meta?.title,
            query: to.query,
        });
    }
    next();
});

export default router;
